

import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import Layout from '../../components/Layout';
import authApi from '../../api/auth';

interface UserProfile {
  id: number;
  gender: string | null;
  avatar: string;
  address: string | null;
  email: string | null;
  userId: number;
  nickName: string;
}

interface UserInfo {
  id: number;
  username: string;
  profile: UserProfile;
}

interface FormData {
  nickName: string;
  email: string;
  gender: string;
  address: string;
  avatar: string;
}

const PersonalInfoPage: React.FC = () => {
  const navigate = useNavigate();
  const avatarInputRef = useRef<HTMLInputElement>(null);
  
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [formData, setFormData] = useState<FormData>({
    nickName: '',
    email: '',
    gender: '',
    address: '',
    avatar: ''
  });
  
  const [loading, setLoading] = useState(true);
  const [showSuccessMessage, setShowSuccessMessage] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    const originalTitle = document.title;
    document.title = '个人信息 - 学途';
    
    // 获取用户信息
    fetchUserInfo();
    
    return () => { document.title = originalTitle; };
  }, []);

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      setLoading(true);
      const response = await authApi.getUser();
      console.log('获取到的用户信息:', response);
      
      if (response && response.data) {
        setUserInfo(response.data);
        const profile = response.data.profile;
        const rawGender = profile?.gender as unknown;
        const genderNum = typeof rawGender === 'number' ? rawGender : (rawGender == null ? null : parseInt(String(rawGender), 10));
        const genderStr = genderNum === 1 ? '男' : genderNum === 0 ? '女' : '';
        
        // 设置表单数据
        setFormData({
          nickName: profile.nickName || '',
          email: profile.email || '',
          gender: genderStr,
          address: profile.address || '',
          avatar: profile.avatar || ''
        });
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 不自动跳转，让用户手动处理登录
    } finally {
      setLoading(false);
    }
  };

  const handleInputChange = (field: keyof FormData, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleAvatarClick = () => {
    avatarInputRef.current?.click();
  };

  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 2 * 1024 * 1024) {
        alert('文件大小不能超过2MB');
        return;
      }
      
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }
      
      const reader = new FileReader();
      reader.onload = (e) => {
        const result = e.target?.result as string;
        setFormData(prev => ({ ...prev, avatar: result }));
        console.log('需要调用第三方接口实现头像上传功能');
      };
      reader.readAsDataURL(file);
    }
  };

  const handleFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.nickName) {
      alert('请填写昵称');
      return;
    }
    
    if (formData.email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(formData.email)) {
        alert('请输入正确的邮箱格式');
        return;
      }
    }
    
    setIsSaving(true);
    
    try {
      if (!userInfo) {
        throw new Error('未获取到用户信息');
      }

      const userId = userInfo.id;
      const profileId = userInfo.profile?.id;
      if (!profileId) {
        throw new Error('未获取到用户资料ID');
      }

      // 性别映射（按你的要求）：男=1，女=0；未设置不传
      let genderVal: number | undefined = undefined;
      if (formData.gender === '男') genderVal = 1;
      else if (formData.gender === '女') genderVal = 0;

      const payload: any = {
        id: profileId,
        address: formData.address || '',
        email: formData.email || '',
        nickName: formData.nickName || '',
      };

      if (typeof genderVal !== 'undefined') {
        payload.gender = genderVal;
      }

      await authApi.updateProfile(userId, payload);

      showSuccessMessageFunc();
      // 刷新一次用户信息以同步最新资料
      await fetchUserInfo();
      console.log('个人信息保存成功', payload);
    } catch (error) {
      console.error('保存失败:', error);
      alert('保存失败，请重试');
    } finally {
      setIsSaving(false);
    }
  };

  const handleReset = () => {
    if (confirm('确定要重置所有修改吗？')) {
      if (userInfo && userInfo.profile) {
        const profile = userInfo.profile;
        const rawGender = profile?.gender as unknown;
        const genderNum = typeof rawGender === 'number' ? rawGender : (rawGender == null ? null : parseInt(String(rawGender), 10));
        const genderStr = genderNum === 1 ? '男' : genderNum === 0 ? '女' : '';
        setFormData({
          nickName: profile.nickName || '',
          email: profile.email || '',
          gender: genderStr,
          address: profile.address || '',
          avatar: profile.avatar || ''
        });
      }
      hideSuccessMessage();
    }
  };

  const showSuccessMessageFunc = () => {
    setShowSuccessMessage(true);
    setTimeout(() => {
      hideSuccessMessage();
    }, 3000);
  };

  const hideSuccessMessage = () => {
    setShowSuccessMessage(false);
  };



  return (
    <Layout title="个人信息 - 学途">
      <div className="flex min-h-screen bg-gray-50">
        {/* 左侧菜单 */}
        <aside className="w-64 bg-white border-r border-gray-200 min-h-screen">
          <nav className="p-4">
            {/* 个人中心菜单 */}
            <div>
              <Link to="/personal-center" className="flex items-center space-x-3 px-4 py-3 mb-4 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg transition-colors">
                <i className="fas fa-user text-lg"></i>
                <span className="font-medium">个人中心</span>
              </Link>
              <ul className="space-y-1">
                <li>
                  <Link to="/personal-info" className="flex items-center space-x-3 px-4 py-2 bg-blue-50 text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-user-edit text-base"></i>
                    <span>个人信息</span>
                  </Link>
                </li>
                <li>
                  <Link to="/enrolled-courses" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-book-open text-base"></i>
                    <span>已报名课程</span>
                  </Link>
                </li>
                <li>
                  <Link to="/messages" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-envelope text-base"></i>
                    <span>站内信</span>
                  </Link>
                </li>
                <li>
                  <Link to="/account-security" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-shield-alt text-base"></i>
                    <span>账户安全</span>
                  </Link>
                </li>
              </ul>
            </div>
          </nav>
        </aside>

        {/* 主内容区域 */}
        <main className="flex-1 min-w-0">
          <div className="max-w-4xl mx-auto px-6 py-8">
            {/* 页面头部 */}
            <div className="mb-8">
              <div className="flex items-center space-x-2 text-sm text-gray-600 mb-2">
                <Link to="/home" className="hover:text-blue-600 transition-colors">首页</Link>
                <i className="fas fa-chevron-right text-xs"></i>
                <Link to="/personal-center" className="hover:text-blue-600 transition-colors">个人中心</Link>
                <i className="fas fa-chevron-right text-xs"></i>
                <span className="text-gray-900">个人信息</span>
              </div>
              <h1 className="text-3xl font-bold text-gray-900">个人信息</h1>
              <p className="text-gray-600 mt-1">查看和修改您的个人基本信息</p>
            </div>

            {/* 成功提示消息 */}
            {showSuccessMessage && (
              <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg mb-6">
                <div className="flex items-center space-x-2">
                  <i className="fas fa-check-circle"></i>
                  <span>个人信息修改成功！</span>
                </div>
              </div>
            )}

            {/* 加载状态 */}
            {loading ? (
              <div className="bg-white rounded-xl shadow-card p-8">
                <div className="flex items-center justify-center py-12">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                  <span className="ml-3 text-text-secondary">加载中...</span>
                </div>
              </div>
            ) : (
              /* 个人信息表单 */
              <div className="bg-white rounded-xl shadow-card p-8">
                <form onSubmit={handleFormSubmit} className="space-y-8">
                  {/* 头像上传区域 */}
                  <div className="space-y-4">
                    <label className="block text-sm font-medium text-text-primary">头像</label>
                    <div className="flex items-center space-x-6">
                      <div 
                    onClick={handleAvatarClick}
                    className="relative cursor-pointer border-2 border-dashed border-gray-300 hover:border-blue-400 rounded-full w-24 h-24 flex items-center justify-center transition-all"
                  >
                        <input 
                          ref={avatarInputRef}
                          type="file" 
                          accept="image/*" 
                          className="hidden"
                          onChange={handleAvatarChange}
                        />
                        {formData.avatar ? (
                          <img 
                            src={formData.avatar}
                            alt="用户头像" 
                            className="w-20 h-20 rounded-full object-cover"
                          />
                        ) : (
                          <div className="w-20 h-20 rounded-full bg-gray-200 flex items-center justify-center">
                            <i className="fas fa-user text-gray-400 text-2xl"></i>
                          </div>
                        )}
                        <div className="absolute inset-0 bg-black bg-opacity-50 rounded-full flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity">
                          <i className="fas fa-camera text-white text-lg"></i>
                        </div>
                      </div>
                      <div>
                        <p className="text-sm text-text-secondary">点击头像更换图片</p>
                        <p className="text-xs text-text-secondary mt-1">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
                      </div>
                    </div>
                  </div>

                  {/* 基本信息 */}
                  <div className="space-y-6">
                    <h3 className="text-lg font-semibold text-text-primary border-b border-border-light pb-2">基本信息</h3>
                    
                    {/* 用户名 */}
                    <div className="space-y-2">
                      <label htmlFor="username" className="block text-sm font-medium text-text-primary">用户名</label>
                      <input 
                        type="text" 
                        id="username" 
                        name="username" 
                        className="w-full px-4 py-3 border border-border-light rounded-lg bg-gray-50 text-text-secondary cursor-not-allowed"
                        value={userInfo?.username || ''}
                        readOnly
                      />
                      <p className="text-xs text-text-secondary">用户名不可修改</p>
                    </div>

                    {/* 昵称 */}
                    <div className="space-y-2">
                      <label htmlFor="nick-name" className="block text-sm font-medium text-text-primary">昵称 *</label>
                      <input 
                        type="text" 
                        id="nick-name" 
                        name="nick-name" 
                        className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                        value={formData.nickName}
                        onChange={(e) => handleInputChange('nickName', e.target.value)}
                        required
                      />
                      <p className="text-xs text-text-secondary">请输入您的昵称</p>
                    </div>

                    {/* 邮箱 */}
                    <div className="space-y-2">
                      <label htmlFor="email" className="block text-sm font-medium text-text-primary">邮箱</label>
                      <input 
                        type="email" 
                        id="email" 
                        name="email" 
                        className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                        value={formData.email}
                        onChange={(e) => handleInputChange('email', e.target.value)}
                        placeholder="请输入邮箱地址"
                      />
                      <p className="text-xs text-text-secondary">用于接收重要通知</p>
                    </div>

                    {/* 性别 */}
                    <div className="space-y-2">
                      <label className="block text-sm font-medium text-text-primary">性别</label>
                      <div className="flex items-center space-x-6">
                        <label className="flex items-center space-x-2 cursor-pointer">
                          <input 
                            type="radio" 
                            name="gender" 
                            value="男" 
                            className="text-primary focus:ring-primary"
                            checked={formData.gender === '男'}
                            onChange={(e) => handleInputChange('gender', e.target.value)}
                          />
                          <span className="text-text-primary">男</span>
                        </label>
                        <label className="flex items-center space-x-2 cursor-pointer">
                          <input 
                            type="radio" 
                            name="gender" 
                            value="女" 
                            className="text-primary focus:ring-primary"
                            checked={formData.gender === '女'}
                            onChange={(e) => handleInputChange('gender', e.target.value)}
                          />
                          <span className="text-text-primary">女</span>
                        </label>
                        <label className="flex items-center space-x-2 cursor-pointer">
                          <input 
                            type="radio" 
                            name="gender" 
                            value="" 
                            className="text-primary focus:ring-primary"
                            checked={!formData.gender}
                            onChange={(e) => handleInputChange('gender', e.target.value)}
                          />
                          <span className="text-text-primary">未设置</span>
                        </label>
                      </div>
                    </div>

                    {/* 地址 */}
                    <div className="space-y-2">
                      <label htmlFor="address" className="block text-sm font-medium text-text-primary">地址</label>
                      <textarea 
                        id="address" 
                        name="address" 
                        rows={3}
                        className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all resize-none"
                        value={formData.address}
                        onChange={(e) => handleInputChange('address', e.target.value)}
                        placeholder="请输入您的地址"
                      />
                      <p className="text-xs text-text-secondary">请输入您的详细地址</p>
                    </div>
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex items-center justify-end space-x-4 pt-6 border-t border-border-light">
                    <button 
                      type="button" 
                      onClick={handleReset}
                      className="px-6 py-3 border border-border-light text-text-secondary rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      重置
                    </button>
                    <button 
                      type="submit" 
                      disabled={isSaving}
                      className="px-6 py-3 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors font-medium disabled:opacity-50"
                    >
                      {isSaving ? '保存中...' : '保存修改'}
                    </button>
                  </div>
                </form>
              </div>
            )}
          </div>
        </main>
      </div>
    </Layout>
  );
};

export default PersonalInfoPage;

